package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.vo.MergePurchaseVo;
import com.atguigu.gulimall.ware.entity.vo.PurchaseDetailDoneVo;
import com.atguigu.gulimall.ware.entity.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.eq("assignee_id",key).or()
                    .eq("id",key).or()
                    .like("assignee_name",key);
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", WareConstant.purchaseStateEnum.CREATED.getCode()).or()
                .eq("status",WareConstant.purchaseStateEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);

    }

    @Override
    public void mergePurchase(MergePurchaseVo mergePurchaseVo) {
        Long purchaseId = mergePurchaseVo.getPurchaseId();
        if (purchaseId == null){//如果没有采购单，需要新建一个采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.purchaseStateEnum.CREATED.getCode());

            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //TODO 判断采购单是否已领取

        List<Long> items = mergePurchaseVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> entitys = items.stream().map(i -> {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(i);
            entity.setPurchaseId(finalPurchaseId);
            entity.setStatus(WareConstant.purchaseDetailStateEnum.ASSIGNED.getCode());

            return entity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(entitys);

        //修改采购单时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    @Transactional
    public void receivedPurchase(List<Long> ids) {
        //1.确认是自己的采购单
        //2.确认采购单是新建或未分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            return item.getStatus() == WareConstant.purchaseStateEnum.CREATED.getCode()
                    ||
                    item.getStatus() == WareConstant.purchaseStateEnum.ASSIGNED.getCode();
        }).map(item -> {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(item.getId());
            purchaseEntity.setStatus(WareConstant.purchaseStateEnum.RECEIVE.getCode());
            purchaseEntity.setUpdateTime(new Date());
            return purchaseEntity;
        }).collect(Collectors.toList());

        //3，更新采购单状态为已领取
        this.updateBatchById(collect);

        //4。跟新采购单中采购项目的状态为正在采购
        collect.forEach(itme->{
            //根据采购单id查询采购项
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(itme.getId());
            List<PurchaseDetailEntity> collect1 = purchaseDetailEntities.stream().map(detail -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(detail.getId());
                entity.setStatus(WareConstant.purchaseDetailStateEnum.BUYING.getCode());

                return entity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect1);
        });
    }

    @Override
    public void donePurchase(PurchaseDoneVo vo) {

        Long id = vo.getId();//采购单id
        //修改采购项状态
        List<PurchaseDetailDoneVo> items = vo.getItems();
        boolean flag = true;
        List<PurchaseDetailEntity> details = new ArrayList<>();
        for (PurchaseDetailDoneVo item : items) {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.purchaseDetailStateEnum.HASERROR.getCode()){
                flag = false;
            }else {
                //采购成功，需要入库，（新增 ，修改）两种状态
                PurchaseDetailEntity byId = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStoke(byId.getSkuId(),byId.getWareId(), byId.getSkuNum());
            }
            entity.setId(item.getItemId());
            entity.setStatus(item.getStatus());
            details.add(entity);
        }
        purchaseDetailService.updateBatchById(details);

        //修改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.purchaseStateEnum.FINISH.getCode():WareConstant.purchaseStateEnum.HASERROR.getCode());
        this.updateById(purchaseEntity);

    }

}